<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>自定义redux</title>
</head>
<body>
  <button onclick="reduce()">-</button>
  <div id="count"></div>
  <button onclick="add()">+</button>
</body>
<script>
  const countID = document.getElementById('count')
  countID.innerHTML = 10
  const countState = {
    count: 10
  }
  const reducer = (state, action) => {
    // 如果state的值是 null ,设置默认值
    if (!state) state = countState
    switch (action.type) {
      case 'REDUCE':
        // 为了返回的是全新的一个对象
        return { ...state, count: state.count - action.payload }
      case 'ADD':
        // 为了返回的是全新的一个对象
        return Object.assign({}, state, { count: state.count + action.payload })
      default:
        return state
    }
  }
  // 定义创建状态管理器方法
  function createStore (reducer) {
    let state = countState
    const getState = () => {
      return state
    }
    // 设置js中的监听器
    let listeners = []

    const dispatch = (action) => {
      state = reducer(state, action)
      // 状态已更新， 让监听器里的所有方法运行
      listeners.forEach(listener => listener())
    }

    const subscribe = (render) => {
      listeners.push(render)
    }

    return {
      getState,
      dispatch,
      subscribe
    }
  }

  // 创建store
  const store = createStore(reducer)

  function render () {
    countID.innerHTML = store.getState().count
  }
  render()

  store.subscribe(render)

  // console.log(store.getState())
  // 定义加减函数
  function reduce () {
    store.dispatch({
      type: 'REDUCE',
      payload: 10
    })
    // 手动更新
    // console.log(store.getState())
    // countID.innerHTML = store.getState().count
  }
  function add () {
    store.dispatch({
      type: 'ADD',
      payload: 10
    })
    // console.log(store.getState())
    // countID.innerHTML = store.getState().count
  }
  /**
   * cnpm i redux -S
   * // 定义状态管理器
   * import { createStore } from 'redux'
   * const reducer = (state= {
   *  count: 10
   * }, action) => {
   *  switch(action.type) {
   *    case 'REDUCE':
   *      return { ...state, count: state.count - action.payload }
   *    case 'ADD':
   *      return { ...state, count: state.count + action.payload }
   *    default: 
   *      return state
   *  }
   * } 
   * 
   * const store = createStore(reducer)
   * 
   * // 订阅更新
   * function render() {
   *  ReactDOM.render(<App />, document.getElementById('root'))
   * }
   * render()
   * store.subscribe(render)
   * 
   * // 使用状态管理器
   * store.getState() { count: 10 }
   * store.dispatch({
   *  type: 'ADD'
   *  payload: 10
   * })
   * */
</script>
</html>